import { Dialog, Form, Button, Loading } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid } from '../../stores/definitionsSendCar';
import { observer } from 'mobx-react-lite';
import { useStore } from '@/hooks';
import DrawerFooter from '@/components/DrawerFooter';

const FromItem = Form.Item;

const SendCarConfirmDialog = (props) => {
  const {
    driverInfo,
    visible,
    onClose,
    onSubmit,
    sendLoading,
  } = props;
  const [formData, setFormData] = useState({});
  const sendCarCtx = useRef({ origin: {}, changed: {} }).current;
  const { ccTaskStore: store } = useStore();
  const {
    code,
    companyId,
    orderInfo,
    taskInfo,
    licenseNo,
    username,
    fullname,
    phone,
    hkPhone = '',
  } = driverInfo || {};

  useEffect(() => {
    initFormData();
  }, [visible]);

  const initFormData = () => {
    const initData = {
      orderId: orderInfo?.id,
      taskId: taskInfo?.id,
      licenseNo,
      carrierDriver: username,
      carrierDriverName: fullname,
      carrierDriverPhone: phone,
      carrierDriverHKPhone: hkPhone,
      carrierCompany: companyId,
      carrierVehicle: code,
      cancelNotice: false,
      intervention: false,
      driverServiceFee: 0,
    };
    sendCarCtx.origin = initData;
    setFormData(initData);
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);
    setFormData({ ...formData });
    sendCarCtx.changed[name] = value == _.get(sendCarCtx.origin.name) ? undefined : value;
  };

  const handleSubmit = (__, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    const { cancelNotice, intervention } = formData;
    if (cancelNotice || intervention) {
      Dialog.confirm({
        content: t`您已干预此任务正常流程，是否继续？`,
        onOk: () => onSubmit(formData),
      });
    } else {
      onSubmit(formData);
    }
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(sendCarCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onClose?.(),
      });
      return;
    }
    onClose?.();
  };

  return (
    <Dialog
      visible={visible}
      title={t`派车确认`}
      onClose={handleCancel}
      onCancel={handleCancel}
      onOk={handleSubmit}
      style={{ width: 500 }}
    >
      <Form
        inline
        isPreview={false}
        value={formData}
        onChange={handleChange}
        useLabelForErrorMessage
      >
        <FieldsGrid
          formData={driverInfo}
          mode="view"
          fields={[
            'showDriver',
            'showCar',
            'sendCarOrderPrice',
            'orderRemark',
          ]}
        />
        <FieldsGrid
          formData={formData}
          mode="edit"
          columns={2}
          fields={['driverServiceFee', 'remark'].concat(fullname == store._mainArgs.notReportDriver.fullname ? ['dispatchRemarks'] : [])}
        />
        {global.isAdmin && <FieldsGrid
          formData={formData}
          mode="edit"
          columns={2}
          fields={['cancelNotice', 'intervention']}
        />}
        <DrawerFooter>
          <FromItem>
            <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>
      </Form>
      {sendLoading && (
        <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}>
          <Loading visible shape="fusion-reactor" />
        </div>
      )}
    </Dialog>
  );
};

export default observer(SendCarConfirmDialog);
